const app = getApp();
const api = require('../../utils/api');

Page({
    data: {
        avatarUrl: '', //头像
        newAvatarUrl: '', //头像
        nickName: '', //昵称
        newNickName: '', //修改昵称

        showEditNickname: false,
        showEditAvatar: false,
    },
    onLoad(options) {

    },onShow() {
        this.getUserInfo();
    },
    getUserInfo() { //获取用户信息
        api.post('/user/info')
            .then(res => {
                this.setData({
                    avatarUrl: res.headImg,
                    nickName: res.nickName,
                    newNickName: res.nickName,
                });
            })
    },

    bindinput(e) { //输入框监听
        let item = e.currentTarget.dataset.item;
        let val = e.detail.value;
        this.setData({
            [item]: val
        });
    },
    openEditNickname() { //打开修改昵称弹窗
        this.setData({
            // newNickName: this.data.nickName,
            showEditNickname: true
        })
    },
    closeEditNickname() {
        this.setData({
            showEditNickname: false
        })
    },
    submitEditNickname() { //提交修改昵称
        console.log(this.data.newNickName)
        if(!this.data.newNickName) {
            wx.showToast({
                title: `请输入昵称`,
                icon: 'none'
            });
            return;
        }
        if(this.data.newNickName.length > 12) {
            wx.showToast({
                title: `昵称不能超过12个字`,
                icon: 'none'
            });
            return;
        }
        if(this.data.newNickName != this.data.nickName) {
            api.post('/user/info/update', {nickName: this.data.newNickName})
                .then(() => {
                    wx.showToast({
                        title: `修改成功`,
                        icon: 'success'
                    });
                    this.getUserInfo();
                    this.closeEditNickname();
                })
        } else {
            wx.showToast({
                title: `修改成功`,
                icon: 'success'
            });
            this.closeEditNickname();
        }
    },

    onChooseAvatar(e) { //选择头像
        let avatarUrl = e.detail.avatarUrl;
        console.log(e.detail)
        api.uploadFileByQiniu(avatarUrl)
            .then(res => {
                let data = JSON.parse(res);
                this.setData({
                    avatarUrl: 'https://file.17wo.cc/' + data.key
                });
                this.submitAvatar();
            })

    },
    submitAvatar() { //上传头像
        api.post('/user/info/update', {headImg: this.data.avatarUrl})
            .then(() => {
                wx.showToast({
                    title: `修改成功`,
                    icon: 'success'
                });
                this.getUserInfo();
            })
    }
})